
const express = require("express");
const knex = require("../../db/config");
const bodyParser = require("body-parser");
const Login = express.Router();
const FNTOOL = require("../../tools/toolfn");
const svgCaptcha = require('svg-captcha')
const nodeMail = require("../../utils/email/index")
const {Base64} = require('js-base64');

const jwt = require("jsonwebtoken");



Login.use(bodyParser.json());
Login.use(express.urlencoded({ extended: true }));
Login.use(express.static(__dirname + "/www"));
Login.use(express.json());


/**
 * 用户信息注册
 * @route POST /create-tenant
 * @group 登录模块 - Operations about user
 * @param {string} tenantName.query.required - 请输入用户名
 * @param {string} tenantEmail.query.required - 请输入邮箱
 * @param {string} tenantPass.query.required - 请输入密码
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
Login.post("/create-tenant", async (req, res) => {
  const { tenantName, tenantEmail,tenantPass } = req.body;
  const isSign = await knex.select().from("tenants").where("tenantEmail", tenantEmail);
  if (isSign.length) {
    res.json({
      isSuccess: false,
      msg: "The email account has been registered.",
      code: 100,
    });
  } else {
    /** 一、插入 tenants 边存入租户信息*/
    const tenantId = tenantName + "_" + FNTOOL();
    const creatTime = new Date().toLocaleString();
    await knex("tenants").insert({tenantId,tenantName,tenantEmail,tenantPass,creatTime,});
    /** 二、 初始该租户下的表  */
    await knex.schema.createTable(`${tenantId}_project`, (table) => {
      table.string("project_id").primary();
      table.string("projectName").notNullable();
      table.integer("latitude");
      table.integer("longitude");
      table.string("description");
      table.string("creationTime");
      table.string("createUserName");
      table.string("projectPhoto");
      table.string("type").notNullable();
    });
    /** 返回租户ID 给前端 请求头携带 租户id */
    res.json({
      isSuccess: true,
      tenantId,
      msg: "Tenant Created And Create Table Over ",
      code: 200,
    });
  }
});
/**
 * 登录
 * @route POST /LoginSync
 * @group 登录模块 - Operation about user
 * @param {string} tenantName.query.required - 请输入用户名
 * @param {string} tenantPass.query.required - 请输入密码
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
Login.post("/LoginSync", async (req, res) => {
  const { tenantEmail, tenantPass } = req.body
  const isSuccess = await knex.select().from("tenants").where("tenantEmail", tenantEmail).where("tenantPass",tenantPass);
  if(isSuccess[0]){
    const token = jwt.sign(Object.assign({}, isSuccess[0]), "zhangkai", { expiresIn: 60 * 60 * 2});
    res.json({
      isSuccess: true,
      token,
      data:{
        tenantInfo: isSuccess[0]
      },
      code: 200,
    });
  }else {
    res.json({
      isSuccess: false,
      msg: "Login fields Please check your username or password",
      code: 200,
    });
  }

});

/**
 * 图形验证码
 * @route GET /Captcha
 * @group 登录模块 - Operations about user
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
Login.get("/Captcha",async (req, res) => {
  const c = svgCaptcha.create({ 
    size: 4, 
    ignoreChars: '0o1i',
    color: true, 
    noise: 1,
    background: '#666' 
  })
  res.json({
    isSuccess: true,
    code:200,
    data:c
  });
});

/**
 * 验证码邮件
 * @route POST /Emails
 * @group 登录模块 - Operations about user
 * @param {string} email.query.required - 请输入邮箱
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
Login.post("/Emails",async (req, res) => {
  const { email }  = req.body;
  const code = String(Math.floor(Math.random() * 10000000)).padEnd(6,'0') // 生成6位随机验证码
  const mail = {
    from: `Keavan"<862779506@qq.com>`,
    subject: '验证码',
    to: email,
    html: `
        <p>您好！</p>
        <p>您的验证码是：<strong style="color:orangered;">${code}</strong></p>
        <p>如果不是您本人操作，请无视此邮件</p>
    ` 
};
await nodeMail.sendMail(mail, (err, info) => {
  if (!err) {
      // res.json({msg: "邮件验证码发送成功",emailCode:Base64.encode(code)})
      knex("email").insert({emailAccount:String(email),emailCode:String(code)})
      // 为了保证邮箱的唯一性，需要在n时间内删除该条记录
      // 5分钟后从数据库中删除（且在5分钟类使用了该验证码则该验证码失效！！！）（从数据库中删除）
      const delay = 1000 * 60 * 5
      timer = setTimeout(()=>{
         knex("email").delete().where({emailAccount:String(email)})
      },delay)
      res.json({code:200,msg: "邮件验证码发送成功"})
  } else {
      res.json({msg: "邮件验证码发送失败，请稍后重试"})
  }
})
});

/**
 * 修改密码
 * @route PUT /UpdatePass
 * @group 登录模块 - Operations about user
 * @param {string} tenantEmail.query.required - 请输入邮箱
 * @param {string} NewPass.query.required - 请输入密码
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
Login.put("/UpdatePass",async (req, res) => {
  const { tenantEmail , NewPass } = req.body
 const IsUpdate = await knex('tenants').where('tenantEmail',tenantEmail).update({tenantPass:NewPass})
 if(IsUpdate){
  res.json({
    isSuccess: true,
    code:200,
    msg: "Password has been Update",
  });
 }else{
  res.json({
    isSuccess: false,
    code:100,
    msg: "error",
  });
 }
});


/**
 * 检查邮箱是否注册
 * @route GET /CheckUser
 * @group 登录模块 - Operations about user
 * @param {string} tenantEmail.query.required - 请输入注册邮箱
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
Login.get("/CheckUser", async (req,res) => {
  const { tenantEmail }  = req.query;
  const isSuccess = await knex.select().from("tenants").where("tenantEmail", tenantEmail);
  if(isSuccess[0]){
    res.json({
      isSuccess: true,
      code:200,
      msg: "User has benn Register",
    });
  }else{
    res.json({
      isSuccess: false,
      code:100,
      msg: "This tenantEmail Dont't has been Register",
    });
  }

})


/**
 * 检查邮箱验证码
 * @route GET /CheckEmailCode
 * @group 登录模块 - Operations about user
 * @param {string} tenantEmail.query.required - 请输入邮箱
 * @param {string} emailCode.query.required - 请输入验证码
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
Login.post("/CheckEmailCode",async (req,res) => {
  const { emailAccount, emailCode } = req.body;
  const result = await knex("email").select().where({emailAccount: String(emailAccount)});
  // 以最后一次接受的验证码为主
  if (
    result[result.length - 1].emailAccount == String(emailAccount) &&
    result[result.length - 1].emailCode == String(emailCode)
  ){
    knex("email").delete().where({emailAccount: String(emailAccount)}).then((res)=> clearTimeout(timer))
    res.json({
      isSuccess: true,
      code:200,
      msg: "Success",
    });
  }else {
    res.json({
      isSuccess: false,
      code:100,
      msg: "验证码错误",
    });
  }

})

/** knex 查询语句  */
Login.post("/getProjectList", async (req, res) => {
  const tenantId = req.tenantId;
  const result = await knex.select().from(`${tenantId}_project`);
  if (result) {
    res.json({
      isSuccess: true,
      data: result,
      msg: "getProjectList success",
    });
  }
});

Login.post("/test", async (req, res) => {
  const tenantId = req.tenantId;
  console.log(tenantId)
  if (tenantId) {
    res.json({
      tenantId
    });
  }
});
// 使用module.exprots导出

module.exports = Login;
